import systems from '../../api/systems'

import {
  SHOW_SUCCESS_MSG,
  SHOW_ERROR_MSG,
  SET_SYSTEMS,
  INSERT_SYSTEM,
  UPDATE_SYSTEM,
  DELETE_SYSTEM
} from '../mutation-types'

// initial state
const state = {
  systems: []
}

// getters
const getters = {
  getSystems: state => state.systems
}

// actions
const actions = {
  //请求业务系统列表
  reqGetSystems({
    commit,
    state
  }) {
    commit(SET_SYSTEMS, {
      systems: []
    })
    systems.getSystems(
      (result) => {
        // debugger;
        if (result.states == 200) {
          commit(SET_SYSTEMS, {
            systems: result.results
          })
        }
      },
      (err) => {
        console.log(err);
      }
    )
  },
  //请求插入系统
  reqInsertSystem({
    commit,
    state
  }, payload) {
    // debugger;
    systems.insertSystem(payload,
      (result) => {
        // debugger;
        if (result.states == 200) {
          commit(SHOW_SUCCESS_MSG, {
            message: '保存业务系统信息成功。',
            duration: 1000,
            needGoBack: true,
          });
        } else if (result.states == 500) {
          commit(SHOW_ERROR_MSG, {
            message: '系统内部错误，请联系系统管理员。'
          });
        }
      },
      (err) => {
        console.log(err);
      }
    )
  },
  //请求更新业务系统
  reqUpdateSystem({
    commit,
    state
  }, payload) {
    // debugger;
    systems.updateSystem(payload,
      (result) => {
        // debugger;
        if (result.states == 200) {
          commit(SHOW_SUCCESS_MSG, {
            message: '保存业务系统信息成功。',
            duration: 1000,
            needGoBack: true,
          });
        } else if (result.states == 500) {
          commit(SHOW_ERROR_MSG, {
            message: '系统内部错误，请联系系统管理员。'
          });
        }
      },
      (err) => {
        console.log(err);
      }
    )
  },
  //请求删除业务系统
  reqDeleteSystem({
    commit,
    state
  }, payload) {
    systems.deleteSystem(payload,
      (result) => {
        // debugger;
        if (result.states == 200) {
          commit(DELETE_SYSTEM, payload._id);
          commit(SHOW_SUCCESS_MSG, {
            message: '删除业务系统成功。',
            duration: 1000
          });
        } else if (result.states == 500) {
          commit(SHOW_ERROR_MSG, {
            message: '系统内部错误，请联系系统管理员。'
          });
        }
      },
      (err) => {
        console.log(err);
      }
    )
  }
}

// mutations
const mutations = {
  [SET_SYSTEMS](state, {
    systems
  }) {
    state.systems = systems
  },
  [UPDATE_SYSTEM](state, user) {
    //TODO??
  },
  [INSERT_SYSTEM](state, user) {
    //TODO??
  },
  [DELETE_SYSTEM](stete, _id) {
    state.systems = state.systems.filter(system => system._id !== _id);
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}

